<template>
  <div id="app">
    <AppNavbar />
    <div class="chat-container">
      <!-- 联系人列表 -->
      <div class="contact-list-container">
        <ContactList
          :contacts="contacts"
          :selected-contact="selectedContact"
          @contact-selected="handleContactSelected"
        />
      </div>

      <!-- 聊天窗口 -->
      <div class="chat-window-container">
        <div class="chat-header" v-if="selectedContact">
          <div class="contact-info">
            <img :src="selectedContact.avatarPath" :alt="selectedContact.contactName" class="contact-avatar" />
            <div>
              <div class="contact-name">{{ selectedContact.contactName }}</div>
              <div class="contact-status">{{ selectedContact.status === 1 ? '在线' : '离线' }}</div>
            </div>
          </div>

          <!-- 添加图标和下拉菜单 -->
          <div class="contact-actions" ref="contactActions">
            <i class="iconfont icon-menu" @click="toggleDropdown"></i>
            <div v-show="showDropdown" class="dropdown-menu" ref="dropdownMenu">
              <div class="dropdown-item" @click="editContactName">修改联系人备注</div>
            </div>
          </div>
        </div>

        <div
          class="chat-messages"
          ref="messagesContainer"
          v-if="selectedContact"
          @scroll="handleScroll"
        >
          <div v-if="loadingHistory" class="loading-history">加载中...</div>
          <div
            v-for="(msg, index) in messages"
            :key="index"
            :class="['message', { sent: msg.isSent, received: !msg.isSent }]"
          >
            <div class="message-content">{{ msg.content }}</div>
            <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
          </div>
        </div>

        <div class="chat-input" v-if="selectedContact">
          <input
            v-model="newMessage"
            @keyup.enter="sendMessage"
            placeholder="输入消息..."
            class="message-input"
          />
          <button @click="sendMessage" :disabled="!newMessage.trim()" class="send-button">
            发送
          </button>
        </div>

        <div class="chat-window empty" v-if="!selectedContact">
          <div class="empty-message">
            请选择一个联系人开始聊天
          </div>
        </div>
      </div>
    </div>

    <!-- 添加修改备注的模态框 -->
    <div v-if="showEditModal" class="modal-overlay" @click="closeEditModal">
      <div class="modal-content" @click.stop>
        <h3>修改联系人备注</h3>
        <input
          v-model="newContactName"
          placeholder="请输入新的备注名"
          class="name-input"
          @keyup.enter="saveContactName"
        />
        <div class="modal-actions">
          <button @click="closeEditModal" class="cancel-btn">取消</button>
          <button @click="saveContactName" class="save-btn">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import AppNavbar from '@/components/AppNavbar.vue'
import ContactList from '@/components/ContactList.vue'
import apiClient from '@/utils/api.js'
import { useWebsocketStore } from '@/store/websocket'

export default {
  name: 'ChatWindow',
  components: {
    AppNavbar,
    ContactList
  },
  data () {
    return {
      contacts: [],
      selectedContact: null,
      newMessage: '',
      messages: [],
      loadingHistory: false,
      hasMoreHistory: true,
      isInitialLoad: true,
      websocketStore: useWebsocketStore(),
      showDropdown: false,
      showEditModal: false,
      newContactName: '',
      editingContact: null,
      isContactsLoaded: false
    }
  },
  async mounted () {
    await this.initChat()
  },
  beforeUnmount () {
    this.websocketStore.removeMessageListener(this.handleWebSocketMessage)
    document.removeEventListener('click', this.handleDocumentClick)
  },
  methods: {
    async initChat () {
      // 确保 WebSocket 连接
      if (!this.websocketStore.isConnected) {
        const token = localStorage.getItem('token')
        if (token) {
          this.websocketStore.connectWebSocket(token)
        }
      }

      this.websocketStore.addMessageListener(this.handleWebSocketMessage)
      document.addEventListener('click', this.handleDocumentClick)

      // 加载联系人列表
      await this.fetchContacts()
      this.isContactsLoaded = true

      // 检查并选择联系人
      await this.checkAndSelectContactFromParams()

      // 监听路由变化
      this.$watch(
        () => this.$route.query.contactId,
        async (newContactId, oldContactId) => {
          if (newContactId !== oldContactId) {
            await this.checkAndSelectContactFromParams()
          }
        }
      )
    },

    async fetchContacts () {
      try {
        const response = await apiClient.get('/chat/getContactList')
        if (response.data.code === '200') {
          this.contacts = response.data.data
        }
      } catch (error) {
        console.error('获取联系人列表失败:', error)
      }
    },

    async checkAndSelectContactFromParams () {
      // 确保联系人列表已加载
      if (!this.isContactsLoaded && this.contacts.length === 0) {
        await this.waitForContacts()
      }

      const contactId = this.$route.query.contactId
      if (contactId) {
        // 查找对应的联系人
        const contact = this.contacts.find(c => c.contactUserId === parseInt(contactId))
        if (contact) {
          await this.handleContactSelected(contact)
        }
      }
    },

    async waitForContacts () {
      // 等待联系人列表加载完成，最多等待3秒
      let attempts = 0
      while (this.contacts.length === 0 && attempts < 30) {
        await new Promise(resolve => setTimeout(resolve, 100))
        attempts++
      }
    },

    async handleContactSelected (contact) {
      this.selectedContact = contact
      this.messages = []
      this.hasMoreHistory = true
      this.isInitialLoad = true

      if (contact) {
        try {
          await apiClient.put(`/chat/updateChatRecordStatus?sendId=${contact.contactUserId}`)

          const contactIndex = this.contacts.findIndex(c => c.contactUserId === contact.contactUserId)
          if (contactIndex !== -1) {
            this.contacts.splice(contactIndex, 1, {
              ...this.contacts[contactIndex],
              unreadMessageCount: 0
            })
          }

          await this.loadHistoryMessages()
        } catch (error) {
          console.error('标记消息为已读失败:', error)
        }
      }
    },

    async handleScroll (event) {
      const { scrollTop } = event.target

      if (scrollTop === 0 && this.hasMoreHistory && !this.loadingHistory) {
        const previousScrollHeight = event.target.scrollHeight
        await this.loadHistoryMessages()

        this.$nextTick(() => {
          const currentScrollHeight = event.target.scrollHeight
          event.target.scrollTop = currentScrollHeight - previousScrollHeight
        })
      }
    },

    async loadHistoryMessages () {
      if (!this.selectedContact || this.loadingHistory || !this.hasMoreHistory) {
        return
      }

      this.loadingHistory = true

      try {
        const response = await apiClient.post('/chat/getChatRecordList', {
          offset: this.messages.length,
          contactId: this.selectedContact.contactUserId
        })

        if (response.data.code === '200') {
          const historyMessages = response.data.data

          if (historyMessages.length === 0) {
            this.hasMoreHistory = false
            return
          }

          // 处理历史消息格式，按时间从早到晚排序
          const formattedMessages = historyMessages.map(record => {
            return {
              content: record.message,
              isSent: record.receiverId === this.selectedContact.contactUserId,
              timestamp: new Date(record.sendTime)
            }
          }).reverse()

          if (this.isInitialLoad) {
            this.messages = formattedMessages
            this.isInitialLoad = false
            this.scrollToBottom()
          } else {
            this.messages = [...formattedMessages, ...this.messages]
          }
        }
      } catch (error) {
        console.error('加载历史消息失败:', error)
      } finally {
        this.loadingHistory = false
      }
    },

    sendMessage () {
      if (!this.newMessage.trim() || !this.selectedContact) {
        return
      }

      const messageData = {
        aimId: this.selectedContact.contactUserId,
        message: this.newMessage,
        type: 'chat'
      }

      // 使用全局 WebSocket 发送消息
      const success = this.websocketStore.sendMessage(messageData)

      if (success) {
        // 本地添加消息
        this.messages.push({
          content: this.newMessage,
          isSent: true,
          timestamp: new Date()
        })

        this.newMessage = ''
        this.scrollToBottom()
      } else {
        console.warn('WebSocket未连接，无法发送消息')
      }
    },

    async handleWebSocketMessage (data) {
      // 判断是否为系统消息
      const isSystemMessage = data.isSystem || data.type === 'system' || data.messageType === 'system'

      // 处理系统消息（用户状态变化）
      if (isSystemMessage) {
        const isOnline = data.message === 'login' || data.status === 'online'
        const userId = data.fromId || data.userId
        this.updateContactStatus(userId, isOnline)
        return
      }

      // 只处理 type 为 chat 的消息
      if (data.type === 'chat') {
        const fromId = data.fromId || data.userId

        if (this.selectedContact && this.selectedContact.contactUserId === fromId) {
          this.messages.push({
            content: data.message,
            isSent: false,
            timestamp: new Date()
          })
          this.scrollToBottom()

          try {
            await apiClient.put(`/chat/updateChatRecordStatus?sendId=${fromId}`)
          } catch (error) {
            console.error('标记消息为已读失败:', error)
          }
        } else {
          const contactIndex = this.contacts.findIndex(c => c.contactUserId === fromId)
          if (contactIndex !== -1) {
            const currentUnreadCount = this.contacts[contactIndex].unreadMessageCount || 0
            const newUnreadCount = Math.min(currentUnreadCount + 1, 99)

            this.contacts.splice(contactIndex, 1, {
              ...this.contacts[contactIndex],
              unreadMessageCount: newUnreadCount
            })
          }
        }
      }
    },

    formatTime (date) {
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    },

    scrollToBottom () {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    },

    updateContactStatus (userId, isOnline) {
      const contactIndex = this.contacts.findIndex(c => c.contactUserId === userId)
      if (contactIndex !== -1) {
        this.contacts.splice(contactIndex, 1, {
          ...this.contacts[contactIndex],
          status: isOnline ? 1 : 0
        })
      }

      if (this.selectedContact && this.selectedContact.contactUserId === userId) {
        this.selectedContact = {
          ...this.selectedContact,
          status: isOnline ? 1 : 0
        }
      }
    },

    toggleDropdown () {
      this.showDropdown = !this.showDropdown
    },

    handleDocumentClick (event) {
      // 如果点击的不是下拉菜单区域，则关闭下拉菜单
      if (this.$refs.contactActions && !this.$refs.contactActions.contains(event.target)) {
        this.showDropdown = false
      }
    },

    editContactName () {
      this.showDropdown = false
      this.editingContact = this.selectedContact
      this.newContactName = this.selectedContact.contactName
      this.showEditModal = true
    },

    closeEditModal () {
      this.showEditModal = false
      this.newContactName = ''
      this.editingContact = null
    },

    async saveContactName () {
      if (!this.newContactName.trim() || !this.editingContact) {
        return
      }

      try {
        const response = await apiClient.post('/chat/updateContactName', {
          contactUserId: this.editingContact.contactUserId,
          contactName: this.newContactName
        })

        if (response.data.code === '200') {
          // 更新联系人列表中的名称
          const contactIndex = this.contacts.findIndex(
            c => c.contactUserId === this.editingContact.contactUserId
          )

          if (contactIndex !== -1) {
            this.contacts.splice(contactIndex, 1, {
              ...this.contacts[contactIndex],
              contactName: this.newContactName
            })
          }

          // 更新当前选中联系人的名称
          if (this.selectedContact &&
              this.selectedContact.contactUserId === this.editingContact.contactUserId) {
            this.selectedContact.contactName = this.newContactName
          }

          this.closeEditModal()
        } else {
          console.error('修改联系人备注失败:', response.data.message)
        }
      } catch (error) {
        console.error('修改联系人备注出错:', error)
      }
    }
  }
}
</script>

<style scoped>
/* 引入阿里巴巴图标库 */
@import '//at.alicdn.com/t/c/font_5004955_gaea9bqopmq.css';

#app {
  background: linear-gradient(to right, #e0f7fa, #ffffff);
  min-height: 100vh;
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-container {
  display: flex;
  flex: 1;
  background-color: #ffffff;
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  height: calc(100vh - 120px);
}

.contact-list-container {
  width: 300px;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
}

.chat-window-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-window {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-window.empty {
  justify-content: center;
  align-items: center;
  flex: 1;
}

.empty-message {
  color: #9e9e9e;
  font-size: 16px;
}

.chat-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.contact-info {
  display: flex;
  align-items: center;
}

.contact-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
}

.contact-name {
  font-weight: 500;
  color: #333;
}

.contact-status {
  font-size: 12px;
  color: #757575;
}

.chat-messages {
  flex: none;
  height: 400px;
  overflow-y: auto;
  padding: 16px;
  background-color: #f9f9f9;
  display: flex;
  flex-direction: column;
  scrollbar-width: thin;
  scrollbar-color: #1976d2 #e0e0e0;
}

/* Webkit浏览器滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 8px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background-color: #1976d2;
  border-radius: 4px;
  border: 2px solid #f1f1f1;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background-color: #1565c0;
}

.message {
  margin-bottom: 16px;
  max-width: 70%;
  display: flex;
  flex-direction: column;
}

.message.sent {
  margin-left: auto;
  align-items: flex-end;
}

.message.received {
  margin-right: auto;
  align-items: flex-start;
}

.message-content {
  padding: 10px 14px;
  border-radius: 18px;
  word-wrap: break-word;
  text-align: left;
  display: inline-block;
  max-width: 100%;
  align-self: flex-start;
}

.message.sent .message-content {
  background-color: #1976d2;
  color: white;
  border-bottom-right-radius: 4px;
}

.message.received .message-content {
  background-color: #e0e0e0;
  color: #333;
  border-bottom-left-radius: 4px;
}

.message-time {
  font-size: 11px;
  color: #9e9e9e;
  margin-top: 4px;
  align-self: flex-end;
}

.chat-input {
  display: flex;
  padding: 16px;
  border-top: 1px solid #e0e0e0;
  background-color: #ffffff;
  flex-shrink: 0;
  gap: 10px; /* 添加间距 */
}

.message-input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  outline: none;
  font-size: 14px;
  transition: all 0.3s ease;
}

.message-input:focus {
  border-color: #1976d2;
  box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
}

.send-button {
  padding: 12px 24px;
  background-color: #1976d2;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.send-button:hover:not(:disabled) {
  background-color: #1565c0;
}

.send-button:disabled {
  background-color: #bbdefb;
  cursor: not-allowed;
}

.loading-history {
  text-align: center;
  padding: 10px;
  color: #9e9e9e;
}

/* 新增样式 */
.contact-actions {
  position: relative;
  margin-left: auto;
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 30px;
  font-style: normal;
  cursor: pointer;
  color: #333; /* 修改为更深的颜色，提高可见性 */
  transition: color 0.3s;
  line-height: 1;
}

.iconfont:hover {
  color: #1976d2;
}

.dropdown-menu {
  position: absolute;
  top: 30px;
  right: 0;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
  min-width: 150px;
  padding: 5px 0;
}

.dropdown-item {
  padding: 10px 15px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
}

.dropdown-item:hover {
  background-color: #f5f5f5;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 300px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modal-content h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
}

.name-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 20px;
  box-sizing: border-box;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.modal-actions button {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  border: none;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #333;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}

.save-btn {
  background-color: #1976d2;
  color: white;
}

.save-btn:hover {
  background-color: #1565c0;
}
</style>
